package com.totem.base.security.model;

import com.totem.base.constants.SecurityComponets;
import com.totem.base.model.Principal;
import com.totem.base.security.Certification;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;

import java.time.Instant;

@NoArgsConstructor
@Data
public class UsernamepasswordCertification implements Certification, Principal {
    private static Argon2PasswordEncoder encoder = SecurityComponets.ARGON2_PASSWORD_ENCODER;
    // token
    private String certification;
    private Long expire;
    private Long expireAt;

    private long id;
    private String username;
    private String password;

    public UsernamepasswordCertification(String u, String p){
        username = u;
        password = p;
    }

    @Override
    public void setExpire(Long expire){
        this.expire = expire;
        Long timestamp = Instant.now().getEpochSecond();
        this.expireAt = timestamp+expire;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        UsernamepasswordCertification that = (UsernamepasswordCertification) o;

        return username.equals(that.username)
                && encoder.matches(password, that.password);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(username).append(password).toHashCode();
    }

    @Override
    public boolean authenticate(Certification anOther) {
        return equals(anOther);
    }

    @Override
    public void setId(long id) {
        this.id = id;
    }
}
